package org.cunamas.web.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileLoad {

    private InputStream uploadedFile;
    private String fileName;
    private String prearchivo;
    
    private String mime;
    private long length;
    private byte[] data;
    private String name;
    private String extension;
    
    private boolean fileExist;
    
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	
	
	public InputStream getUploadedFile() {
		return uploadedFile;
	}
	public void setUploadedFile(InputStream uploadedFile) {
		this.uploadedFile = uploadedFile;
	}
	public String getPrearchivo() {
		return prearchivo;
	}
	public void setPrearchivo(String prearchivo) {
		this.prearchivo = prearchivo;
	}
	
	/**
	 * 
	 * @return
	 */
	public Boolean saveToDisk() {
  
		boolean validate = true;
		FileOutputStream fos = null;

		try {

			File parentDir = new File(prearchivo);
			if (!parentDir.exists()) {
				// create the parent dirs
				parentDir.mkdirs();
			}
			StringBuilder sb = new StringBuilder();
			sb.append(getPrearchivo()).append(File.separator).append(fileName);
			File file = new File(sb.toString());

			sb = null;

			fos = new FileOutputStream(file);
			byte[] b = new byte[102400];
			int readCnt = 0;

			while ((readCnt = getUploadedFile().read(b)) != -1) {
				fos.write(b, 0, readCnt);
				validate = true;
				fos.flush();

			}

		} catch (Throwable ex) {
			ex.printStackTrace();
			validate = false;

		} finally {
			try {
				fos.close();

			} catch (IOException ex) {
				validate = false;
			}
		}

		fileExist = validate;

		return validate;
	}
	
	public String getMime() {
		return mime;
	}
	public void setMime(String mime) {
		this.mime = mime;
	}
	public long getLength() {
		return length;
	}
	public void setLength(long length) {
		this.length = length;
	}
	public byte[] getData() {
		return data;
	}
	public void setData(byte[] data) {
		this.data = data;
	}
	public String getExtension() {
		return extension;
	}
	public void setExtension(String extension) {
		this.extension = extension;
	}
	public boolean isFileExist() {
		return fileExist;
	}
	public void setFileExist(boolean fileExist) {
		this.fileExist = fileExist;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
